package org.jeecg.modules.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.entity.MesSalaryCalculationRecord;
import org.jeecg.modules.mes.service.IMesSalaryCalculationService;
import org.jeecg.modules.mes.vo.MesSalaryCalculationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 薪资计算控制器
 * @Author: jeecg-boot
 * @Date: 2025-09-03
 * @Version: V1.0
 */
@Api(tags="薪资计算管理")
@RestController
@RequestMapping("/mes/salaryCalculation")
@Slf4j
public class MesSalaryCalculationController extends JeecgController<MesSalaryCalculationRecord, IMesSalaryCalculationService> {

    @Autowired
    private IMesSalaryCalculationService salaryCalculationService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "薪资计算记录-分页列表查询")
    @ApiOperation(value="薪资计算记录-分页列表查询", notes="薪资计算记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesSalaryCalculationRecord>> queryPageList(MesSalaryCalculationRecord salaryCalculationRecord,
                                                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                   HttpServletRequest req) {
        QueryWrapper<MesSalaryCalculationRecord> queryWrapper = QueryGenerator.initQueryWrapper(salaryCalculationRecord, req.getParameterMap());
        Page<MesSalaryCalculationRecord> page = new Page<MesSalaryCalculationRecord>(pageNo, pageSize);
        IPage<MesSalaryCalculationRecord> pageList = salaryCalculationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 计算单个任务参与者薪资
     */
    @AutoLog(value = "计算单个任务参与者薪资")
    @ApiOperation(value="计算单个任务参与者薪资", notes="计算单个任务参与者薪资")
    @PostMapping(value = "/calculateTaskSalary")
    public Result<MesSalaryCalculationVO> calculateTaskSalary(@RequestParam String participantId) {
        try {
            MesSalaryCalculationVO result = salaryCalculationService.calculateTaskSalary(participantId);
            if ("success".equals(result.getCalculationStatus())) {
                return Result.OK("薪资计算成功", result);
            } else {
                return Result.error(result.getErrorMessage());
            }
        } catch (Exception e) {
            log.error("计算薪资失败", e);
            return Result.error("计算薪资失败：" + e.getMessage());
        }
    }

    /**
     * 批量计算任务薪资
     */
    @AutoLog(value = "批量计算任务薪资")
    @ApiOperation(value="批量计算任务薪资", notes="批量计算任务薪资")
    @PostMapping(value = "/calculateBatchTaskSalary")
    public Result<List<MesSalaryCalculationVO>> calculateBatchTaskSalary(@RequestParam String taskId) {
        try {
            List<MesSalaryCalculationVO> results = salaryCalculationService.calculateBatchTaskSalary(taskId);
            return Result.OK("批量薪资计算完成", results);
        } catch (Exception e) {
            log.error("批量计算薪资失败", e);
            return Result.error("批量计算薪资失败：" + e.getMessage());
        }
    }

    /**
     * 计算员工日薪资
     */
    @AutoLog(value = "计算员工日薪资")
    @ApiOperation(value="计算员工日薪资", notes="计算员工日薪资")
    @GetMapping(value = "/calculateDailySalary")
    public Result<List<MesSalaryCalculationVO>> calculateDailySalary(
            @RequestParam String employeeId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date calculationDate) {
        try {
            List<MesSalaryCalculationVO> results = salaryCalculationService.calculateDailySalary(employeeId, calculationDate);
            return Result.OK("日薪资计算完成", results);
        } catch (Exception e) {
            log.error("计算日薪资失败", e);
            return Result.error("计算日薪资失败：" + e.getMessage());
        }
    }

    /**
     * 计算员工月薪资
     */
    @AutoLog(value = "计算员工月薪资")
    @ApiOperation(value="计算员工月薪资", notes="计算员工月薪资")
    @GetMapping(value = "/calculateMonthlySalary")
    public Result<List<MesSalaryCalculationVO>> calculateMonthlySalary(
            @RequestParam String employeeId,
            @RequestParam int year,
            @RequestParam int month) {
        try {
            List<MesSalaryCalculationVO> results = salaryCalculationService.calculateMonthlySalary(employeeId, year, month);
            return Result.OK("月薪资计算完成", results);
        } catch (Exception e) {
            log.error("计算月薪资失败", e);
            return Result.error("计算月薪资失败：" + e.getMessage());
        }
    }

    /**
     * 根据员工ID和日期范围查询薪资记录
     */
    @AutoLog(value = "查询员工薪资记录")
    @ApiOperation(value="查询员工薪资记录", notes="根据员工ID和日期范围查询薪资记录")
    @GetMapping(value = "/getSalaryRecords")
    public Result<List<MesSalaryCalculationRecord>> getSalaryRecords(
            @RequestParam String employeeId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        try {
            List<MesSalaryCalculationRecord> records = salaryCalculationService.getSalaryRecordsByEmployeeAndDateRange(employeeId, startDate, endDate);
            return Result.OK("查询成功", records);
        } catch (Exception e) {
            log.error("查询薪资记录失败", e);
            return Result.error("查询薪资记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据任务ID查询薪资记录
     */
    @AutoLog(value = "根据任务查询薪资记录")
    @ApiOperation(value="根据任务查询薪资记录", notes="根据任务ID查询薪资记录")
    @GetMapping(value = "/getSalaryRecordsByTask")
    public Result<List<MesSalaryCalculationRecord>> getSalaryRecordsByTask(@RequestParam String taskId) {
        try {
            List<MesSalaryCalculationRecord> records = salaryCalculationService.getSalaryRecordsByTaskId(taskId);
            return Result.OK("查询成功", records);
        } catch (Exception e) {
            log.error("查询任务薪资记录失败", e);
            return Result.error("查询任务薪资记录失败：" + e.getMessage());
        }
    }

    /**
     * 计算员工日期范围薪资
     */
    @AutoLog(value = "计算员工日期范围薪资")
    @ApiOperation(value="计算员工日期范围薪资", notes="计算员工在指定日期范围内的薪资统计")
    @GetMapping(value = "/calculateRangeSalary")
    public Result<Map<String, Object>> calculateRangeSalary(
            @RequestParam String employeeId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        try {
            Map<String, Object> rangeSalaryStats = new HashMap<>();
            double totalSalary = 0.0;

            //calculationDate大于等于开始时间 小于等于结束时间
            LambdaQueryWrapper<MesSalaryCalculationRecord> wrapper = new LambdaQueryWrapper<MesSalaryCalculationRecord>();
            wrapper.eq(MesSalaryCalculationRecord::getEmployeeId, employeeId)
                    .ge(MesSalaryCalculationRecord::getCalculationDate, startDate)
                    .le(MesSalaryCalculationRecord::getCalculationDate, endDate);
            List<MesSalaryCalculationRecord> dailyResults = salaryCalculationService.list(wrapper);
            //计算日期内薪资总和 
            for (MesSalaryCalculationRecord record : dailyResults) {
                totalSalary += record.getPieceSalary().doubleValue();
            }
            rangeSalaryStats.put("totalSalary", Math.round(totalSalary * 100.0) / 100.0);
            rangeSalaryStats.put("taskCount", dailyResults.size());
            rangeSalaryStats.put("startDate", startDate);
            rangeSalaryStats.put("endDate", endDate);
            
            return Result.OK("日期范围薪资计算完成", rangeSalaryStats);
        } catch (Exception e) {
            log.error("计算日期范围薪资失败", e);
            return Result.error("计算日期范围薪资失败：" + e.getMessage());
        }
    }

    /**
     * 获取按员工分组的薪资数据（树形结构）
     */
    @AutoLog(value = "获取按员工分组的薪资数据")
    @ApiOperation(value="获取按员工分组的薪资数据", notes="获取按员工分组的薪资数据，用于树形表格显示")
    @GetMapping(value = "/getGroupedSalaryData")
    public Result<?> getGroupedSalaryData(MesSalaryCalculationRecord salaryCalculationRecord,
                                         @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                         @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                         HttpServletRequest req) {
        try {
            return salaryCalculationService.getGroupedSalaryData(salaryCalculationRecord, pageNo, pageSize, req);
        } catch (Exception e) {
            log.error("获取分组薪资数据失败", e);
            return Result.error("获取分组薪资数据失败：" + e.getMessage());
        }
    }
}
